// 初始化 sidePanel
chrome.sidePanel
  .setPanelBehavior({ openPanelOnActionClick: false })
  .catch((error) => console.error(error));

// 监听快捷键
chrome.commands.onCommand.addListener((command) => {
  if (command === 'open-dialog') {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]) {
        // 根据存储的窗口显示方式决定打开方式
        chrome.storage.local.get(['windowStyle'], function(result) {
          const style = result.windowStyle || 'float';
          if (style === 'float') {
            // 发送消息给content script打开全局窗口
            chrome.tabs.sendMessage(tabs[0].id, { action: 'openDialog' });
          } else {
            // 打开侧边栏
            chrome.sidePanel.open({ windowId: tabs[0].windowId });
          }
        });
      }
    });
  }
});

// 监听来自 content script 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'openPopup') {
    // 打开 popup 页面
    chrome.action.openPopup();
  } else if (request.action === 'openSidePanel') {
    chrome.sidePanel.open({ windowId: sender.tab.windowId })
      .then(() => {
        sendResponse({ success: true });
      })
      .catch((error) => {
        console.error('Error opening side panel:', error);
        sendResponse({ success: false, error: error.message });
      });
    return true;
  }
});

// 修改请求拦截器
chrome.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    // 添加必要的头部
    let headers = details.requestHeaders;
    
    // 添加 SameSite 和 Secure 属性
    headers.push({
      name: 'Access-Control-Allow-Origin',
      value: '*'
    });
    
    // 添加 CORS 头部
    headers.push({
      name: 'Access-Control-Allow-Credentials',
      value: 'true'
    });
    
    // 添加自定义头部用于身份验证
    chrome.storage.local.get(['userToken'], function(result) {
      if (result.userToken) {
        headers.push({
          name: 'Authorization',
          value: result.userToken
        });
      }
    });
    
    return { requestHeaders: headers };
  },
  { urls: ["https://ai.yinlimedia.com/*"] },
  ["blocking", "requestHeaders", "extraHeaders"]
);

// 获取用户 token
async function getUserToken() {
  return new Promise((resolve) => {
    chrome.storage.local.get(['userToken'], function(result) {
      resolve(result.userToken);
    });
  });
}

// 处理 CORS 预检请求
chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    if (details.method === "OPTIONS") {
      return {
        redirectUrl: "data:,"
      };
    }
  },
  { urls: ["https://ai.yinlimedia.com/*"] },
  ["blocking"]
);